#include "stdafx.h"
#include "ShaderManager.h"
#include "Shader.h"


CShaderManager::CShaderManager()
: m_CgContext(0)
{
	m_CgContext = cgCreateContext();
	cgD3D9SetDevice(g_pDevice);
	cgD3D9RegisterStates(m_CgContext);
}

CShaderManager::~CShaderManager()
{
	//	destroy shaders
	for (TShadersMap::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
		delete it->second;

	cgDestroyContext(m_CgContext);
}

IShader* CShaderManager::CreateShader(const char* name)
{
	if (!m_CgContext)
		return nullptr;

	//	if shader already exist - return it
	IShader* shader = GetShader(name);
	if (!shader)
	{
		//	else - create new one
		shader = new CShader(m_CgContext);
		string filename = string(SHADERS_DIR) + name + ".cgfx";
		if (shader->Load(filename.c_str()))
			m_shaders[name] = shader;
		else
			SAFE_DELETE(shader);
	}
	return shader;
}

IShader* CShaderManager::GetShader(const char* name) const
{
	TShadersMap::const_iterator it = m_shaders.find(name);
	return it != m_shaders.end() ? it->second : nullptr;
}
